#include "thread_pool.h"

// rmdirCommand 函数的实现
void rmdirCommand(task_t *task) {
    struct stat st;
    if (stat(task->data, &st) == -1) {
        perror("stat");
        return;
    }

    if (S_ISREG(st.st_mode)) {
        if (remove(task->data) != 0) {
            perror("删除文件失败");
        }
    } else if (S_ISDIR(st.st_mode)) {
        if (remove_directory(task->data) != 0) {
            perror("删除目录失败");
        }
    }
}

// remove_directory 函数的实现
int remove_directory(const char *path) {
    struct dirent *entry;
    DIR *dir = opendir(path);

    if (dir == NULL) {
        perror("opendir");
        return -1;
    }

    while ((entry = readdir(dir)) != NULL) {
        char full_path[1024] = {0};
        struct stat statbuf;

        // 跳过 "." 和 ".."
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);

        if (stat(full_path, &statbuf) == -1) {
            perror("获取文件状态失败");
            closedir(dir);
            return -1;
        }

        if (S_ISREG(statbuf.st_mode)) {
            if (remove(full_path) != 0) {
                perror("删除文件失败");
                closedir(dir);
                return -1;
            }
        } else if (S_ISDIR(statbuf.st_mode)) {
            if (remove_directory(full_path) != 0) {
                closedir(dir);
                return -1;
            }
        }
    }

    closedir(dir);

    if (rmdir(path) != 0) {
        perror("删除目录失败");
        return -1;
    }

    return 0;
}